package com.tcoiss.webservice.apiServer.xstream.mapper;

public class AbstractXmlFriendlyMapper extends MapperWrapper {

  private char dollarReplacementInClass = '-';
  private String dollarReplacementInField = "_DOLLAR_";
  private String underscoreReplacementInField = "__";
  private String noPackagePrefix = "default";

  protected AbstractXmlFriendlyMapper(Mapper wrapped) {
    super(wrapped);
  }

  protected String escapeClassName(String _className) {
    String className = _className;
    className = className.replace('$', dollarReplacementInClass);
    if (className.charAt(0) == dollarReplacementInClass) {
      className = noPackagePrefix + className;
    }
    return className;
  }

  protected String unescapeClassName(String _className) {
    String className = _className;
    if (className.startsWith(noPackagePrefix + dollarReplacementInClass)) {
      className = className.substring(noPackagePrefix.length());
    }
    className = className.replace(dollarReplacementInClass, '$');
    return className;
  }

  protected String escapeFieldName(String fieldName) {
    StringBuffer result = new StringBuffer();
    int length = fieldName.length();
    for (int i = 0; i < length; i++) {
      char c = fieldName.charAt(i);
      if (c == '$') {
        result.append(dollarReplacementInField);
      } else if (c == '_') {
        result.append(underscoreReplacementInField);
      } else {
        result.append(c);
      }
    }
    return result.toString();
  }

  protected String unescapeFieldName(String xmlName) {
    StringBuffer result = new StringBuffer();
    int length = xmlName.length();
    for (int i = 0; i < length; i++) {
      char c = xmlName.charAt(i);
      if (stringFoundAt(xmlName, i, underscoreReplacementInField)) {
        i += underscoreReplacementInField.length() - 1;
        result.append('_');
      } else if (stringFoundAt(xmlName, i, dollarReplacementInField)) {
        i += dollarReplacementInField.length() - 1;
        result.append('$');
      } else {
        result.append(c);
      }
    }
    return result.toString();
  }

  private boolean stringFoundAt(String name, int i, String replacement) {
    if (name.length() >= i + replacement.length()
        && name.substring(i, i + replacement.length()).equals(replacement)) {
      return true;
    }
    return false;
  }

}
